import {AxiosResponse} from "axios";
import {AppRequestInterface, InternalRequestConfig,} from "./app-request-type.ts";
import AppRequestUtil from "./app-request-util.ts";

let tokenValid = true;

/**
 * 响应成功拦截器，2xx范围内的状态码都会触发该函数。不能使用箭头函数，否则无this
 * @param axiosResponse {
 *  status: 来自服务器响应的HTTP状态码
 *  statusText: 来自服务器响应的HTTP状态信息
 *  data: 由服务器提供的响应
 *  headers: 服务器响应头。header名都是小写，而且可以使用方括号语法访问，例如`response.headers['content-type']`
 *  config: axios的请求配置信息
 *  request: 生成此响应的请求。Nodejs中为最后一个ClientRequest实例，浏览器中为XMLHttpRequest实例
 * }
 */
const handleResponseFulfilled = function handleResponseFulfilled(
    this: AppRequestInterface,
    axiosResponse: AxiosResponse
) {
  // 2xx 范围内的状态码都会触发该函数
  // log.debug("AxiosResponse：{}", axiosResponse);

  const requestConfig = axiosResponse.config as InternalRequestConfig;
  const serverResponse = axiosResponse.data;

  // loading
  const showLoading =
      typeof requestConfig.showLoading === "function"
          ? requestConfig.showLoading()
          : requestConfig.showLoading;

  // 二进制数据
  if (serverResponse instanceof Blob) {
    if (showLoading) {
      requestConfig.hideLoadingFunction(true);
    }
    return Promise.resolve(axiosResponse);
  }

  const passedData = requestConfig.passFullResponse
      ? axiosResponse
      : serverResponse;

  // 文本数据
  const contentType = axiosResponse.headers["content-type"];
  if (!contentType.includes("application/json")) {
    if (showLoading) {
      requestConfig.hideLoadingFunction(true);
    }
    return Promise.resolve(passedData);
  }

  // 业务判定
  let isServerSuccess = false;
  if (AppRequestUtil.isMocked(requestConfig.url, this.mockConfig)) {
    isServerSuccess = true;
  } else {
    isServerSuccess =
        typeof requestConfig.isServerSuccess === "function"
            ? requestConfig.isServerSuccess(serverResponse)
            : requestConfig.isServerSuccess;
  }

  if (isServerSuccess) {
    // log.debug("业务成功");
    if (showLoading) {
      requestConfig.hideLoadingFunction(true);
    }
    const showSuccessMsg =
        typeof requestConfig.showSuccessMsg === "function"
            ? requestConfig.showSuccessMsg()
            : requestConfig.showSuccessMsg;
    if (showSuccessMsg) {
      requestConfig.showSuccessMsgFunction(
          requestConfig.successMsg(serverResponse)
      );
    }
    return Promise.resolve(passedData);
  }

  // log.debug("业务失败");
  if (showLoading) {
    requestConfig.hideLoadingFunction(false);
  }
  const showFailureMsg =
      typeof requestConfig.showFailureMsg === "function"
          ? requestConfig.showFailureMsg()
          : requestConfig.showFailureMsg;
  if (showFailureMsg && tokenValid) {
    requestConfig.showFailureMsgFunction(
        requestConfig.failureMsg(serverResponse)
    );
  }

  const isTokenInvalid =
      typeof requestConfig.isTokenInvalid === "function"
          ? requestConfig.isTokenInvalid(serverResponse)
          : requestConfig.isTokenInvalid;
  if (isTokenInvalid) {
    tokenValid = false;
    requestConfig.handleTokenInvalid();
  } else {
    tokenValid = true;
  }

  return Promise.reject(passedData);
};

export default handleResponseFulfilled;
